import React, { useState, useEffect, useRef } from 'react';
import { useRequest, useModel } from 'umi';
import { Row, Card,Image, message} from 'antd';
import { getMonitoringDevicInfo, getMonitoringPhase } from '@/services/deviceLive';

import moment from 'moment'
import ECharts from 'echarts-for-react';


import {alarmcode} from '@/utils/alarmcode-enum';
import AlarmTable from '@/pages/monitoring/deviceAlarm';
import DeviceRunState from '@/pages/monitoring/deviceRunState';


import styles from './index.less';


import slg from '@/assets/img/img/slg.png';
import item1 from '@/assets/img/img/item1.png';
import item2 from '@/assets/img/img/item2.png';
import item3 from '@/assets/img/img/item3.png';
import item4 from '@/assets/img/img/item4.png';
import item5 from '@/assets/img/img/item5.png';
import item6 from '@/assets/img/img/item6.png';
import item7 from '@/assets/img/img/item7.png';
import item8 from '@/assets/img/img/item8.png';
import item91 from '@/assets/img/img/item9-1.png';
import item92 from '@/assets/img/img/item9-2.png';



const details: React.FC = (props: any) => {
  const { params } = props.match;

  const second = useRequest(() => {
    return getMonitoringPhase({...params,type:2});
  }, {
    pollingInterval: 3000,
    pollingWhenHidden: false
  });



  const [deviceInfo, setDeviceInfo] = useState<API.DeviceItem>({});
  const [runningData, setRunningData] = useState({});

  const [chartIndex, setChartIndex] = useState(4);

  const [onLineBackgroundColor, setOnLineBackgroundColor] = useState('#8ca1aa');
  const [alarmBackgroundColor, setAlarmBackgroundColor] = useState('#8ca1aa');
  const [tripBackgroundColor, setTripBackgroundColor] = useState('#8ca1aa');



  const { initialState,setInitialState } = useModel('@@initialState');
  const { mySocket,dicts,currentUser } = initialState || {};

  if (mySocket&&mySocket.ws.readyState==1) {
    mySocket.send(params.id);
    mySocket.onmessage =async function (e) {
     // console.log(`onmessage: ${e.data}`);
      //排除心跳数据
    if ("heartbeat" != e.data&&e.data.indexOf("AlarmData")!=-1) {
        const data = JSON.parse(e.data);
        await setInitialState((s) => ({ ...s, alarmNotices: data.AlarmData }));
      }else  if("heartbeat" != e.data){
        onMessage(e);
      }
    };
  }

  const onMessage = (e:any) => {
   

    const message = JSON.parse(e.data);
   // const runningData = {...message.RunningData, ...message.ReliabilityData}
    const rData = message.RunningData||{};
    console.log(rData)

    if(rData.deviceId!=params.id){
      return;
     }
    // console.log(rData)
    rData.acquisitionTime = moment().format("YYYY-MM-DD HH:mm:ss");
    if(runningData?.online==0&&rData?.online==1){
       go();
    }
    if(runningData?.alarm==0&&rData?.alarm==1){
        go1();
    }
    if(runningData?.trip==0&&rData?.trip==1){
        go2();
    }
    setRunningData(rData);
  }


  useEffect(() => {
    const setSelectData = async () => {
      var details = await getMonitoringDevicInfo(params);

      setRunningData(details.runningData);
      setDeviceInfo(details.deviceInfo);
      if(details.runningData?.online==1){
        await go();
      }
      if(details.runningData?.alarm==1){
        await  go1();
      }
      if(details.runningData?.trip==1){
        await  go2();
      }
    }
    setSelectData();
 
  }, []);

  const sleep = (t) => {
    return new Promise((res,rej)=>{
        setTimeout(res,t)
    })
}

  async function  go() {
    setOnLineBackgroundColor("yellow");
    await sleep(200)
    setOnLineBackgroundColor("#19377f");
    await  sleep(200)
    go()
}


async function  go1() {
  setAlarmBackgroundColor("red");
  await sleep(300)
  setAlarmBackgroundColor("#19377f");
  await  sleep(300)
  go1()
}
async function  go2() {
  setTripBackgroundColor("red");
  await sleep(300)
  setTripBackgroundColor("#19377f");
  await  sleep(300)
  go2()
}


  const option2 = {
    color: ["red", "green", "yellow"],
    grid: {
      top: 50,
      left: 60,
      right: 50,
      bottom: 30
    },
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      // data: [second.data?.series[0].name, second.data?.series[1].name, second.data?.series[2].name],
      textStyle: {
        color: '#ddd',
      },
    },
    toolbox: {
      show: false,
    },
    xAxis: {
    
      type: 'category',
      boundaryGap: false,
      data: second.data?.phaseTime,
      splitLine: {
        show: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    yAxis: {
      type: 'value',
     // min:0,  //取0为最小刻度
      // max: 60, //取100为最大刻度
      axisLabel: {
        formatter: '{value}'
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    series: second.data?.data
  };
  
  const option3 = {
    color: ["red", "green", "yellow"],
    grid: {
      top: 50,
      left: 60,
      right: 50,
      bottom: 30
    },
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      // data: [second.data?.series[0].name, second.data?.series[1].name, second.data?.series[2].name],
      textStyle: {
        color: '#ddd',
      },
    },
    toolbox: {
      show: false,
    },
    xAxis: {
    
      type: 'category',
      boundaryGap: false,
      data: second.data?.phaseTime,
      splitLine: {
        show: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    yAxis: {
      type: 'value',
      scale:true,
      min:0,  //取0为最小刻度
      axisLabel: {
        formatter: '{value}'
      },
      minInterval:1,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    series: second.data?.data1
  };


 



  return (
    <div className={styles.main} key={1}>
     
     <div  className={styles.flexBetween} style={{    marginRight: '10px',    alignItems: 'end'}}>
     <div className={styles.flexBetween} style={{flex:5,    alignItems: 'end'}}>
        <div style={{flex:  1}}> 
          <div  className={styles.flex}>  
            <Image    src={slg}  preview={false} />
            <div className={styles.deviceInfo} >
                <div>
                  <span  className={styles.title} > {deviceInfo?.deviceName||'--'} </span>
                  <span className={styles.updateTimeText} > (最新同步时间：{runningData?.acquisitionTime||'--'})</span>
                </div>
                <div className={styles.flexBetween} > 
                  <div>  
                    <span>设备位号：{deviceInfo?.deviceNo||'--'} </span>  
                    <span>&nbsp;  安装位置：{deviceInfo?.areaName||'--'}{deviceInfo?.devicePosition}</span>
                  </div>
                  <div>最新维保日期:{deviceInfo?.latestMaintenanceTime}</div>
                </div>  
            </div>
          </div>
          {/* <div>  
            <span>设备位号：{deviceInfo?.deviceNo||'--'} </span>  
            <span>&nbsp;  安装位置：{deviceInfo?.areaName||'--'}{deviceInfo?.devicePosition||'--'}</span>
          </div>         */}
        </div>
        {/* <div>最新维保日期:{deviceInfo?.latestMaintenanceTime}</div> */}
      </div>
      <div  className={styles.flexBetween} style={{flex:3}}>
        <div  className={ [styles.flexBetween, styles.stateL].join(' ')}>
          <div>
            <div  className={runningData?.start==1? [styles.yuan, styles.bgGreen].join(' '):styles.yuan} ></div>
            <span>启动</span>
          </div>
          <div>
            <div  className={runningData?.startARunning==1? [styles.yuan, styles.bgGreen].join(' '):styles.yuan} ></div>
            <span>启动A</span>
          </div>
          <div>
          <div  className={runningData?.startBRunning==1? [styles.yuan, styles.bgGreen].join(' '):styles.yuan} ></div>
            <span>启动B</span>
          </div>
        </div>
        <div  className={ [styles.flexBetween, styles.stateR].join(' ')}>
          <div>
          <div  className={runningData?.running==1? [styles.yuan, styles.bgGreen].join(' '):styles.yuan} ></div>
            <span>运行</span>
          </div>
          <div>
            <div  className={runningData?.alarm==1? [styles.yuan, styles.bgRed].join(' '):styles.yuan} ></div>
            <span>报警</span>
          </div>
          <div>
            <div  className={runningData?.trip==1? [styles.yuan, styles.bgRed].join(' '):styles.yuan} ></div>
            <span>故障</span>
          </div>
          <div>
            <div  className={runningData?.online==1? [styles.yuan, styles.bgYellow].join(' '):styles.yuan} style={{backgroundColor:onLineBackgroundColor}}></div>
            <span>通讯</span>
          </div>
        </div>
      </div>
     </div>
     <div  className={styles.flexBetween} style={{    margin: '12px 0 30px 0'}}>
      <div  style={{flex:5}}>
        <div className={styles.flex} >
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item1}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div className={styles.middleValue}><span className={styles.data} >{runningData?.totalStart==null?"--":runningData?.totalStart}</span><span className={styles.unit}>次</span></div>
            <div className={styles.attribute}>总启动次数</div>
          </div>
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item2}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div  className={styles.middleValue}><span className={styles.data} >{runningData?.totalTrip==null?"--":runningData?.totalTrip}</span><span className={styles.unit}>次</span></div>
            <div className={styles.attribute}>总跳闸次数</div>
          </div>
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item3}  preview={false} /> <span className={styles.topRight} >本次运行{runningData?.currentRuningHour==null?"--":runningData?.currentRuningHour}小时</span></div>
            <div className={styles.middleValue}><span className={styles.data} >{runningData?.totalRuningHour==null?"--":runningData?.totalRuningHour}</span><span className={styles.unit}>小时</span></div>
            <div className={styles.attribute}>累计运行时间</div>
          </div>
        </div>
        <div className={styles.flex} >
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item4}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div className={styles.middleValue}><span className={styles.data} >{runningData?.activePower==null?"--":runningData?.activePower}</span><span className={styles.unit}>kW</span></div>
            <div className={styles.attribute}>有功功率P</div>
          </div>
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item5}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div className={styles.middleValue}><span className={styles.data} >{runningData?.reactivePower==null?"--":runningData?.reactivePower}</span><span className={styles.unit}>kvar</span></div>
            <div className={styles.attribute}>无功功率Q</div>
          </div>
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item6}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div className={styles.middleValue}><span className={styles.data} >{runningData?.apparentPower==null?"--":runningData?.apparentPower}</span><span className={styles.unit}>kVA</span></div>
            <div className={styles.attribute}>视在功率S</div>
          </div>
        </div>
        <div className={styles.flex} >
        <div   style={{flex:1}}>
          <div  className={styles.dataItem} style={{height:'220px'}}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item7}  preview={false} /> <span className={styles.topRight} >电流不平衡率
            {runningData?.currentUnbalance==null?"--":runningData?.currentUnbalance}%</span></div>
            <div> 
              <div style={{margin: '5px 0 -7px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}><span><span  className={styles.nameItalic} >I</span>a</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.phaseaCurrent==null?"--":runningData?.phaseaCurrent}</span>A</div></div>
              <div style={{margin: '0 0 -7px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}><span><span  className={styles.nameItalic} >I</span>b</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.phasebCurrent==null?"--":runningData?.phasebCurrent}</span>A</div></div>
              <div style={{margin: '0 0 -6px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}><span><span  className={styles.nameItalic} >I</span>c</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.phasecCurrent==null?"--":runningData?.phasecCurrent}</span>A</div></div>
            </div>
            <div className={styles.attribute} style={{marginTop:'10px'}}>三相电流</div>
          </div>
          </div>
          <div   style={{flex:1}}>
          <div  className={styles.dataItem} style={{height:'220px'}}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item8}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div> 
              <div style={{margin: '5px 0 -7px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}><span ><span className={styles.nameItalic} >U</span>ab</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.uabLineVoltage==null?"--":runningData?.uabLineVoltage}</span>V</div></div>
              <div style={{margin: '0 0 -7px 10px',color:'rgb(64 255 255)'}}   className={styles.flex}><span ><span className={styles.nameItalic}>U</span>bc</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.ubcLineVoltage==null?"--":runningData?.ubcLineVoltage}</span>V</div></div>
              <div style={{margin: '0 0 -6px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}><span ><span className={styles.nameItalic}>U</span>ac</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.ucaLineVoltage==null?"--":runningData?.ucaLineVoltage}</span>V</div></div>
            </div>
            <div className={styles.attribute} style={{marginTop:'10px'}}>线电压</div>
          </div>
          </div>
          <div   style={{flex:1}}>
            <div  className={styles.dataItem}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item91}  preview={false} /> <span className={styles.topRight} >{runningData?.powerFactor>=80?'高于':'低于'}80%</span></div>
              <div className={styles.middleValue}><span className={styles.data} >{runningData?.powerFactor==null?"--":runningData?.powerFactor}</span><span className={styles.unit}>%</span></div>
              <div className={styles.attribute}>功率因数cos</div>
            </div>
            <div  className={styles.dataItem} style={{marginTop:"10px"}}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item92}  preview={false} /> <span className={styles.topRight} >{runningData?.heatCapacityPercentage>=80?'高于':'低于'}80%</span></div>
              <div className={styles.middleValue}><span className={styles.data} >{runningData?.heatCapacityPercentage==null?"--":runningData?.heatCapacityPercentage}</span><span className={styles.unit}>%</span></div>
              <div className={styles.attribute}>热容量百分比</div>
            </div>
          </div>
        </div>
    
      </div>
      <div className={styles.flex} style={{flex:3}}>
        <Card   className={ styles.alarmBox}  >
          <div className={styles.title1}>报警指示</div>
          <div className={styles.content} >
          {Object.keys(alarmcode).map((key ,index) => (
             <div className={styles.flex} ><div className={styles.yuan}   style={runningData?.alarmCode==key?{backgroundColor:alarmBackgroundColor}:{}}></div><span className={styles.baojingText}>{alarmcode[key]}报警</span></div>
            ))}
         </div>
        </Card>
        <Card    className={ styles.alarmBox}  >
        <div className={styles.title1}>跳闸指示</div>
        <div className={styles.content}>
          {Object.keys(alarmcode).map((key ,index) => (
             <div className={styles.flex} ><div className={styles.yuan}   style={runningData?.tripCode==key?{backgroundColor:tripBackgroundColor}:{}}></div><span className={styles.baojingText}>{alarmcode[key]}故障</span></div>
            ))}
         </div>
        </Card>
      </div>
      </div>
 
     
      <Row style={{marginRight: '0' }} key={6}>
   
        <div className={styles.tabsTitle}>
          <a className={chartIndex != 4 ? styles.a1 : [styles.a1, styles.tabcheck1].join(' ')} onClick={() => setChartIndex(4)} > 运行状态</a>
          <div className={ chartIndex != 4 ? styles.a1after : [styles.a1after, styles.a1afterCheck].join(' ') }></div>
          <a className={chartIndex!=1?styles.a2:[styles.a2,styles.tabcheck].join(' ')}   onClick={()=>setChartIndex(1)} >三相电流趋势分析</a>
          <a className={chartIndex!=2?styles.a2:[styles.a2,styles.tabcheck].join(' ')}   onClick={()=>setChartIndex(2)}> 三相电压趋势分析</a>
          <a className={chartIndex!=3?styles.a3:[styles.a3,styles.tabcheck].join(' ')}  onClick={()=>setChartIndex(3)}> 报警信息</a>
        </div>
        <Card  className={ styles.modalItem} title={null} style={{width:"100%"}} >
          <ECharts  style={{display:chartIndex==1?'block':'none'}}   option={option2} />
          <ECharts  style={{display:chartIndex==2?'block':'none'}} option={option3} />
          <AlarmTable deviceId={params.id} display={chartIndex==3?'block':'none'}></AlarmTable>

          <DeviceRunState  deviceId={params.id} display={chartIndex==4?'block':'none'} />
         </Card>
       
      </Row>
    
       
    </div>
  );
};

export default details;